import Vue from 'vue'
import Vuex from 'vuex'
import { setToken, getToken } from '@/utils/cookies.js'
import { login, register } from '@/api/user.js'
Vue.use(Vuex);

// const getDefaultState = () => {
//     return {
//         name: null,
//         token: null
//     }
//   }

// const state = getToken() || getDefaultState()

const state = {
    user: getToken() || {}
}

const mutations={
    SET_TOKEN: (state, user) => {
        console.log(state)
        state.user.userId = user.userId
        state.user.userName = user.userName
    }
    // SET_NAME: (state, name) => {
    //     state.name = name;
    // },
    // SET_USER: (state, user) => {
    //     state.user = user;
    // }
}
const actions={
    Login({commit}, user) {
        // console.log(user)
        return new Promise((resolve, reject) => {
        // 向后端发送请求，验证用户名密码是否正确，请求成功接收后端返回的token值，利用commit修改store的state属性，并将token存放在localStorage中
        login(user)
          .then(resp => {
            const user = {
                userId: resp.data.userId,
                userName: resp.data.userName
            }
            commit('SET_TOKEN', user)
            setToken(user)
            // commit("SET_TOKEN", resp.data.userId);
            // setToken(resp.data.userId)
            // setName(resp.data.userName)
            resolve(resp.data)
          })
          .catch(err => {
            reject(err)
          })
        })
    },
    // 注册
    Register({commit}, user) {
        // console.log(user)
        return new Promise((resolve, reject) => {
        // 向后端发送请求，验证用户名密码是否正确，请求成功接收后端返回的token值，利用commit修改store的state属性，并将token存放在localStorage中
        register(user)
          .then(resp => {
            const user = {
                userId: resp.data.userId,
                userName: resp.data.userName
            }
            commit('SET_TOKEN', user)
            setToken(user)
            // commit("SET_TOKEN", resp.data.userId);
            // setToken(resp.data.userId)
            // setName(resp.data.userName)
            resolve(resp.data)
          })
          .catch(err => {
            reject(err)
          })
        })
    }
}
// const handleLoginSuccess = ({ commit }, data) => {
//     const user = {
//       token: data.userToken,
//       id: data.userIdentification,
//       userName: data.userName,
//       nickName: data.nickName,
//       realName: data.realName,
//       avatar: data.headImage,
//       mobile: data.mobile
//     }
//     commit('SAVE_USER', user)
//     setToken(user)
// }
export default new Vuex.Store({
    state,
    mutations,
    actions
})